package com.situ.filter;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.situ.entity.User;

//登录相关的filter
@WebFilter(urlPatterns = "/*")
public class LoginFilter implements Filter {

	@Override
	public void init(FilterConfig filterConfig) throws ServletException {
		// TODO Auto-generated method stub
		System.out.println("login filter init.....");
	}

	@Override
	public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
		HttpServletRequest req = (HttpServletRequest) request;
		HttpServletResponse resp = (HttpServletResponse) response;
		String uri = req.getRequestURI();// 查看当前请求的地址或者资源
		if (uri.startsWith("/css/") || uri.startsWith("/js/") || uri.startsWith("/plugins/") || uri.contains("login")) {
			chain.doFilter(request, response);
		} else {
			User u = (User) req.getSession().getAttribute("curr");
			boolean isLogin = (u != null);// 是否已登录
			if (isLogin) {
				chain.doFilter(request, response);
			} else {
				resp.sendRedirect("/login.jsp");
			}
		}
	}

	@Override
	public void destroy() {
		// TODO Auto-generated method stub

	}

}
